package org.lanyu.springainovel.common.service;

import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.lanyu.springainovel.novel.entity.BookAnalysisTask;
import org.lanyu.springainovel.novel.entity.BookAnalysisRecord;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.simp.SimpMessagingTemplate;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

/**
 * WebSocket服务类，用于发送任务进度更新和通知
 */
@Slf4j
@Service
public class WebSocketService {

    @Autowired
    private SimpMessagingTemplate messagingTemplate;
    
    @Autowired
    private ObjectMapper objectMapper;

    /**
     * 发送任务进度更�?     * @param taskId 任务ID
     * @param progress 进度百分�?     * @param message 进度消息
     */
    public void sendTaskProgress(Long taskId, int progress, String message) {
        try {
            Map<String, Object> payload = new HashMap<>();
            payload.put("taskId", taskId);
            payload.put("progress", progress);
            payload.put("message", message);
            payload.put("timestamp", System.currentTimeMillis());
            
            // 发送到特定任务的主�?
            messagingTemplate.convertAndSend("/topic/book-analysis/progress/" + taskId, payload);
            
            log.debug("发送任务进度更�? taskId={}, progress={}, message={}", taskId, progress, message);
        } catch (Exception e) {
            log.error("发送任务进度更新失�? taskId={}", taskId, e);
        }
    }

    /**
     * 发送任务状态更�?     * @param task 任务对象
     */
    public void sendTaskStatusUpdate(BookAnalysisTask task) {
        try {
            Map<String, Object> payload = new HashMap<>();
            payload.put("taskId", task.getId());
            payload.put("projectId", task.getProjectId());
            payload.put("status", task.getStatus());
            payload.put("progress", task.getProgress());
            payload.put("errorMessage", task.getErrorMessage());
            payload.put("startTime", task.getStartTime());
            payload.put("endTime", task.getEndTime());
            payload.put("timestamp", System.currentTimeMillis());
            
            // 发送到特定任务的主�?
            messagingTemplate.convertAndSend("/topic/book-analysis/status/" + task.getId(), payload);
            
            // 发送到项目的主�?
            messagingTemplate.convertAndSend("/topic/book-analysis/project/" + task.getProjectId() + "/tasks", payload);
            
            log.debug("发送任务状态更�? taskId={}, status={}", task.getId(), task.getStatus());
        } catch (Exception e) {
            log.error("发送任务状态更新失�? taskId={}", task.getId(), e);
        }
    }

    /**
     * 发送任务完成通知
     * @param task 任务对象
     */
    public void sendTaskCompletion(BookAnalysisTask task) {
        try {
            Map<String, Object> payload = new HashMap<>();
            payload.put("taskId", task.getId());
            payload.put("projectId", task.getProjectId());
            payload.put("status", task.getStatus());
            payload.put("progress", task.getProgress());
            payload.put("timestamp", System.currentTimeMillis());
            
            // 根据任务状态设置不同的消息
            if ("completed".equals(task.getStatus())) {
                payload.put("message", "任务已完成");
            } else if ("failed".equals(task.getStatus())) {
                payload.put("message", "任务失败: " + task.getErrorMessage());
            } else {
                payload.put("message", "任务状态更�? " + task.getStatus());
            }
            
            // 发送到特定任务的主�?
            messagingTemplate.convertAndSend("/topic/book-analysis/completion/" + task.getId(), payload);
            
            // 发送到项目的主�?
            messagingTemplate.convertAndSend("/topic/book-analysis/project/" + task.getProjectId() + "/notifications", payload);
            
            log.info("发送任务完成通知: taskId={}, status={}", task.getId(), task.getStatus());
        } catch (Exception e) {
            log.error("发送任务完成通知失败: taskId={}", task.getId(), e);
        }
    }
    
    /**
     * 发送记录进度更新
     * @param recordId 记录ID
     * @param progress 进度百分比
     * @param message 进度消息
     */
    public void sendRecordProgress(Long recordId, int progress, String message) {
        try {
            Map<String, Object> payload = new HashMap<>();
            payload.put("recordId", recordId);
            payload.put("progress", progress);
            payload.put("message", message);
            payload.put("timestamp", System.currentTimeMillis());
            
            // 发送到特定记录的主题
            messagingTemplate.convertAndSend("/topic/book-analysis/progress/" + recordId, payload);
            
            log.debug("发送记录进度更新: recordId={}, progress={}, message={}", recordId, progress, message);
        } catch (Exception e) {
            log.error("发送记录进度更新失败: recordId={}", recordId, e);
        }
    }
    
    /**
     * 发送记录状态更新
     * @param record 记录对象
     */
    public void sendRecordStatusUpdate(BookAnalysisRecord record) {
        try {
            Map<String, Object> payload = new HashMap<>();
            payload.put("recordId", record.getId());
            payload.put("status", record.getStatus());
            payload.put("progress", record.getProgress());
            payload.put("errorMessage", record.getErrorMessage());
            payload.put("startTime", record.getStartTime());
            payload.put("endTime", record.getEndTime());
            payload.put("timestamp", System.currentTimeMillis());
            
            // 发送到特定记录的主�?
            messagingTemplate.convertAndSend("/topic/book-analysis/record/status/" + record.getId(), payload);
            
            log.debug("发送记录状态更�? recordId={}, status={}", record.getId(), record.getStatus());
        } catch (Exception e) {
            log.error("发送记录状态更新失�? recordId={}", record.getId(), e);
        }
    }
    
    /**
     * 发送记录完成通知
     * @param record 记录对象
     */
    public void sendRecordCompletion(BookAnalysisRecord record) {
        try {
            Map<String, Object> payload = new HashMap<>();
            payload.put("recordId", record.getId());
            payload.put("status", record.getStatus());
            payload.put("progress", record.getProgress());
            payload.put("timestamp", System.currentTimeMillis());
            
            // 根据记录状态设置不同的消息
            if ("completed".equals(record.getStatus())) {
                payload.put("message", "分析已完成");
            } else if ("failed".equals(record.getStatus())) {
                payload.put("message", "分析失败: " + record.getErrorMessage());
            } else {
                payload.put("message", "分析状态更�? " + record.getStatus());
            }
            
            // 发送到特定记录的主�?
            messagingTemplate.convertAndSend("/topic/book-analysis/record/completion/" + record.getId(), payload);
            
            log.info("发送记录完成通知: recordId={}, status={}", record.getId(), record.getStatus());
        } catch (Exception e) {
            log.error("发送记录完成通知失败: recordId={}", record.getId(), e);
        }
    }
}
